package com.cskaoyan.processor;

import com.cskaoyan.bean.Animal;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author stone
 * @date 2022/11/12 09:36
 */
@Component
public class AnimalProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        //if (bean instanceof Animal) {// 切入点
        if (match("rule1",bean)) {// 切入点

            Object proxy = Enhancer.create(bean.getClass(), new InvocationHandler() {
                @Override
                public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                    if ("toString".equals(method.getName())) {
                        return method.invoke(bean, objects);
                    }
                    if (match2("rule2",method)) {

                        Object invoke = customAdvice(method, objects, bean);
                        return invoke;
                    }

                    return method.invoke(bean, objects);
                }
            });
            return proxy;
        }
        return bean;
    }

    private Object customAdvice(Method method, Object[] objects, Object bean) throws IllegalAccessException, InvocationTargetException {
        System.out.println("hello:" + method.getName());
        Object invoke = method.invoke(bean, objects);
        System.out.println("world:" + method.getName());
        return invoke;
    }

    private boolean match(String rule,Object bean) {
        // 判断bean是否符合要求
        return true;
    }
    private boolean match2(String rule,Method method) {
        // 判断方法是否符合要求
        return true;
    }
}
